<template>
  <div class="notice-center">
    <div class="box-top">
      <el-form>
        <el-form-item label="消息标题">
          <el-input clearable placeholder="请输入标题" v-model="noticeName"></el-input>
        </el-form-item>
        <el-form-item label="状态">
          <el-select clearable v-model="status" placeholder="请选状态">
            <el-option v-for="(item, i) in statusList" :key="i" :label="item.name" :value="item.value"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="currentPage=1;init()">查询</el-button>
          <el-button @click="handleReset">重置</el-button>
        </el-form-item>
      </el-form>
    </div>
    <!--列表-->
      <div class="box-mid">
        <el-button type="primary" @click="handleAdd(true)">新增</el-button>
      </div>
      <div class="box-table">
        <el-table v-loading="loading" border :data="tableData" tooltip-effect="dark">
            <el-table-column align="center" prop="title" label="标题"></el-table-column>
            <el-table-column align="center" label="消息图片" show-overflow-tooltip width="200px">
              <template slot-scope="scope">
                <img class="my-img" :src="scope.row.cover" @click="clickImg(scope.row.cover)" alt="">
              </template>
            </el-table-column>
            <el-table-column align="center" label="创建时间">
              <template slot-scope="scope">
                <span>{{$moment(Number(scope.row.create_time)).format('YYYY-MM-DD')}}</span>
              </template>
            </el-table-column>
            <el-table-column align="center" label="状态" prop="status">
              <template slot-scope="scope">
                <el-switch v-model="scope.row.zhStatus" @change="enableSetChange(scope.row)"></el-switch>
              </template>
            </el-table-column>
            <el-table-column align="center">
              <template slot-scope="scope">
                <el-button @click="handleAdd(false, scope.row)" type="text">修改</el-button>
                <el-button @click="handleDel(scope.row)" type="text">删除</el-button>
              </template>
            </el-table-column>
        </el-table>
      </div>
      <div class="box-pagenation">
        <el-pagination @current-change="handleCurrentChange" :current-page="currentPage" :page-size="pageSize" layout="total, prev, pager, next, jumper" :total="total"></el-pagination>
      </div>
    <!--轮播新增区域-->
    <el-dialog :title="title" :visible.sync="dialogVisible" width="700px">
      <el-form :model="ruleForm" :rules="rules" label-width="100px" ref="ruleForm" class="ruleForm">
        <el-form-item label="消息标题" prop="title">
          <el-input clearable placeholder="请输入消息标题" v-model="ruleForm.title"></el-input>
        </el-form-item>
        <el-form-item class="avatar-uploader" label="消息图片" prop="cover">
          <el-upload action="/v1/common/uploadImage" :on-success="uploadSuccess" :multiple="false" :headers="headers" :show-file-list="false">
            <img v-if="imgPath" :src="imgPath" class="avatar">
            <i v-else class="el-icon-plus avatar-uploader-icon"></i>
          </el-upload>
        </el-form-item>
        <el-form-item label="消息内容" prop="content">
          <Editor id="tinymce" placeholder="请输入内容" v-model="ruleForm.content" :init="editorInit"></Editor>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="submitForm">确 定</el-button>
      </span>
    </el-dialog>
    <el-dialog title="图片预览" :visible.sync="showImg">
      <img class="show-img" :src="imgPath" alt="">
    </el-dialog>
  </div>
</template>
<script>
import { mapActions } from 'vuex'
import tinymce from 'tinymce/tinymce'
import 'tinymce/themes/modern/theme'
import Editor from '@tinymce/tinymce-vue'
import 'tinymce/plugins/image' // 富文本图片插件
import 'tinymce/plugins/link' // 富文本外链插件
export default {
  name: 'NoticeCenter',
  components: { Editor },
  data () {
    return {
      dialogVisible: false,
      title: '新增消息',
      ruleForm: { // 表单
        title: '', // 消息标题
        cover: '', // 消息图片hash
        content: '' // 消息富文本框内容
      },
      editorInit: { // 富文本编辑器默认状态
        language_url: '/tinymce/zh_CN.js',
        language: 'zh_CN',
        skin_url: '/tinymce/skins/lightgray',
        height: 300,
        plugins: 'link image' // 富文本编辑器增加外链和图片选项
      },
      noticeName: '',
      statusList: [
        { name: '正常', value: '1' },
        { name: '禁用', value: '2' }
      ],
      headers: {
        'access-token': localStorage.getItem('token') || ''
      },
      rules: {
        title: [
          { required: true, message: '请输入消息标题', trigger: 'blur' }
        ],
        cover: [
          { required: true, message: '请上消息图片', trigger: 'change' }
        ],
        content: [
          { required: true, message: '请输入消息内容', trigger: 'blur' }
        ]
      },
      status: '',
      id: null,
      showImg: false,
      imgPath: '',
      loading: false,
      total: 0,
      pageSize: 10,
      currentPage: 1,
      tableData: []
    }
  },
  created () {
    tinymce.init({})
    this.init()
  },
  methods: {
    ...mapActions({
      getInitData: 'noticeManage/getArticleList',
      updateStatus: 'noticeManage/updateArticleStatus',
      delact: 'noticeManage/delArticle',
      add: 'noticeManage/addArticle',
      update: 'noticeManage/updateArticle'
    }),
    handleReset () {
      this.noticeName = ''
      this.status = ''
    },
    submitForm () {
      this.$refs['ruleForm'].validate((valid) => {
        if (valid) {
          this.updateData()
        } else {
          return false
        }
      })
    },
    updateData () {
      let str = this.title === '新增消息' ? 'add' : 'update'
      if (this.title === '新增消息') {
        str = 'add'
      } else {
        str = 'update'
        this.ruleForm.article_id = this.id
      }
      this[str](this.ruleForm).then(res => {
        if (res) {
          this.init()
          this.$message.success('保存成功')
          this.dialogVisible = false
        }
      })
    },
    uploadSuccess (res) {
      if (res.code === 0) {
        this.$message.success('图片上传成功')
        this.ruleForm.cover = res.data.url
        this.imgPath = res.data.url
      }
    },
    clickImg (url) {
      this.imgPath = url
      this.showImg = true
    },
    init () {
      const params = {
        page: this.currentPage,
        size: this.pageSize,
        status: this.status,
        keyword: this.noticeName
      }
      this.loading = true
      this.getInitData(params).then(res => {
        const { items, count } = res
        this.tableData = items
        this.total = count
        this.tableData.forEach(item => {
          this.$set(item, 'zhStatus', item.status === '1')
        })
      }).finally(() => {
        this.loading = false
      })
    },
    handleCurrentChange (val) {
      this.currentPage = val
      this.init()
    },
    handleSizeChange (val) {
      this.pageSize = val
      this.init()
    },
    // 修改状态
    enableSetChange (row) {
      let params = {
        article_id: row.article_id,
        status: row.status === '1' ? '2' : '1'
      }
      this.updateStatus(params).then(res => {
        this.$message({
          type: 'success',
          message: '消息状态修改成功!'
        })
      })
    },
    handleAdd (isNew, item) {
      this.dialogVisible = true
      if (isNew) {
        this.imgPath = ''
        this.title = '新增消息'
        let data = this.$refs['ruleForm']
        if (data) {
          data.resetFields()
        }
      } else {
        this.title = '修改消息'
        this.id = item.article_id
        this.imgPath = item.cover
        this.ruleForm = {
          title: item.title,
          cover: item.cover,
          content: item.content
          // status: item.status
        }
      }
    },
    handleDel (item) { // 删除消息
      let params = {
        article_id: item.article_id
      }
      this.delact(params).then(res => {
        this.$message.success('删除成功')
        this.init()
      })
    }
  }
}
</script>
<style lang="less">
  .notice-center {
    .my-img {
      width: 100%;
      border: none;
      cursor: pointer;
    }
    .show-img {
      width: 100%;
      border: none;
    }
  }
</style>
